package tt.dz.biz.service.Job;

import java.io.InputStream;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;
import java.util.Map;
import org.apache.avro.Protocol;
import org.apache.avro.Protocol.Message;
import org.apache.avro.generic.GenericData;
import org.apache.avro.generic.GenericData.Record;
import org.apache.avro.generic.GenericRecord;
import org.apache.avro.ipc.NettyTransceiver;
import org.apache.avro.ipc.generic.GenericRequestor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import tt.dz.common.LogUtil;
import tt.dz.common.SMSMessageUtil;

@Service("heartBeatClientService")
public class HeartBeatClientService
{
  @Value("${ms.rpc.serverPort}")
  private int port;
  @Value("${monitor.mobile}")
  private String mobileNos;
  @Value("${rpc.heartbeat.msg}")
  private String message;
  private static Protocol protocol;
  private static NettyTransceiver client;
  private static InetAddress ia;
  private static String localname;
  
  static
  {
    try
    {
      ia = InetAddress.getLocalHost();
      localname = ia.getHostName();
    }
    catch (UnknownHostException localUnknownHostException) {}
  }
  
  public void execHearBeat()
  {
    try
    {
      if (null == protocol)
      {
        InputStream in = getClass().getClassLoader().getResourceAsStream("msAvro.json");
        protocol = Protocol.parse(in);
      }
      client = new NettyTransceiver(new InetSocketAddress("localhost", Integer.valueOf(this.port).intValue()));
      GenericRequestor requestor = new GenericRequestor(protocol, client);
      GenericRecord request = new GenericData.Record(((Protocol.Message)protocol.getMessages().get("hearBeat")).getRequest());
      request.put("req", "hello");
      Object result = requestor.request("hearBeat", request);
      if (!"successful".equals(result.toString())) {
        sendMonitorMsg();
      }
    }
    catch (Exception e)
    {
      LogUtil.error("测试心跳客户端异常", e);
      sendMonitorMsg();
    }
    finally
    {
      client.close();
    }
  }
  
  public void sendMonitorMsg()
  {
    try
    {
      if (StringUtils.isNotBlank(this.mobileNos))
      {
        String[] mobiles = this.mobileNos.split(",");
        for (String mobile : mobiles) {
          SMSMessageUtil.sendMessage(mobile, this.message + "【" + localname + "(" + getIP() + ")】");
        }
      }
    }
    catch (Exception e)
    {
      LogUtil.error("心跳监控短信发送失败", e);
    }
  }
  
  protected String getIP()
  {
    StringBuilder ipSb = new StringBuilder();
    Enumeration allNetInterfaces = null;
    try
    {
      allNetInterfaces = NetworkInterface.getNetworkInterfaces();
    }
    catch (SocketException e)
    {
      LogUtil.error("获取本机网络服务异常");
    }
    InetAddress ip = null;
    Enumeration addresses = null;
    NetworkInterface netInterface = null;
    while (allNetInterfaces.hasMoreElements())
    {
      netInterface = (NetworkInterface)allNetInterfaces.nextElement();
      addresses = netInterface.getInetAddresses();
      while (addresses.hasMoreElements())
      {
        ip = (InetAddress)addresses.nextElement();
        if ((ip != null) && ((ip instanceof Inet4Address))) {
          ipSb.append(ip.getHostAddress()).append("||");
        }
      }
    }
    return ipSb.toString();
  }
}
